from flask import Blueprint, request, render_template, session, redirect, g
from decorators import login_required
from exts import db
from models import Question, Answer
from .forms import QuestionForm, AnswerForm

bp = Blueprint('qa', __name__, url_prefix='/qa')

# 发布问答
@bp.route('/publish', methods=['GET','POST'])
@login_required # 装饰器，会把当前函数作为参数传给装饰器，装饰器会把装饰器的返回值赋值给被装饰的函数
def publish():
    if request.method == 'GET':
        return render_template('publish.html')
    else:
        form = QuestionForm(request.form)
        if form.validate():
            question = Question()
            question.title = form.title.data
            question.content = form.content.data
            question.author = g.user # 当前登录的用户
            db.session.add(question)
            try:
                db.session.commit()
            except Exception as e:
                db.session.rollback()
                print(e)
            return redirect('/')
        else:
            print(form.errors)
            return redirect('/qa/publish')

@bp.route('/detail/<int:question_id>')
@login_required
def detail(question_id):
    question = Question.query.get(question_id)
    return render_template('detail.html', question=question)

@bp.route('/answer/<int:question_id>',methods=['POST'])
@login_required
def answer(question_id):
    form = AnswerForm(request.form)
    if form.validate():
        answer = Answer(content=form.content.data, author_id=g.user.id, question_id=question_id)
        db.session.add(answer)
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            print(e)
    return redirect(f'/qa/detail/{question_id}')

@bp.route('/search/<string:search_value>')
def search(search_value):
    questions = Question.query.filter(Question.title.contains(search_value))
    return render_template('index.html',questions=questions)
